package com.zw.pdm.module.afterSale.Service;



import com.zw.pdm.base.BaseService;
import com.zw.pdm.entity.sys.User;
import com.zw.pdm.module.afterSale.mapper.CheckDao;
import com.zw.pdm.module.afterSale.model.CheckModel;
import com.zw.pdm.module.afterSale.model.FileModel;
import com.zw.pdm.module.afterSale.model.ProjectModel;
import com.zw.pdm.util.CommonUtils;
import com.zw.pdm.util.FileUtils;
import com.zw.pdm.util.ShiroUtils;
import com.zw.pdm.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;


@Service
public class CheckService extends BaseService {

    @Autowired
    private CheckDao checkDao;


    @Value("${user.upload.path}")
    private String uploadPath;

    /**
     * 上传临时文件
     */
    public String uploadTemp(MultipartFile file) {
        if (null != file) {
            StringBuffer sb = new StringBuffer();
            sb.append(uploadPath);
            sb.append(ShiroUtils.getLoginName());
            sb.append("/temp/");
            String fileName = FileUtils.upload(file, sb.toString());
            if (CommonUtils.isNotNull(fileName)) {
                logService.saveLog("上传临时文件", "名称：" + fileName);
                return sb.toString() + fileName;
            }
        }
        return null;
    }

    /**
     * @Description: selectUnCheckList 查询待发起验收列表
     * @Author: zcb
     * @Date: 2020-12-26 10:20:53
     * @Param: []
     * @Return: java.util.List<com.zhongwang.sale.module.afterSale.model.ProjectModel>
     **/
    public List<ProjectModel> selectUnCheckList(ProjectModel projectModel) {
        return checkDao.selectUnCheckList(projectModel);
    }

    /**
     * @Description: selectUnCheckList 查询已发起验收列表
     * @Author: zcb
     * @Date: 2020-12-26 10:20:53
     * @Param: []
     * @Return: java.util.List<com.zhongwang.sale.module.afterSale.model.ProjectModel>
     **/
    public List<ProjectModel> selectCheckList(ProjectModel projectModel) {
        User user = ShiroUtils.getUser();
        projectModel.setLoginName(user.getName());
        return checkDao.selectCheckList(projectModel);
    }

    /**
     * @Description: selectCheckExamineList 待审核验收列表
     * @Author: zcb
     * @Date: 2021-01-05 15:06:33
     * @Param: [projectModel]
     * @Return: java.util.List<com.zhongwang.sale.module.afterSale.model.ProjectModel>
     **/
    public List<ProjectModel> selectCheckExamineList(ProjectModel projectModel) {
        return checkDao.selectCheckExamineList(projectModel);
    }

    /**
     * @Description: queryList 验收单查询页面
     * @Author: zcb
     * @Date: 2021-01-05 20:05:39
     * @Param: [projectModel]
     * @Return: java.util.List<com.zhongwang.sale.module.afterSale.model.ProjectModel>
     **/
    public List<ProjectModel> queryList(ProjectModel projectModel) {
        return checkDao.queryList(projectModel);
    }

    /**
     * @Description: insertNewCheck 验收单据表新增一条记录
     * @Author: zcb
     * @Date: 2020-12-26 13:38:36
     * @Param: [model]
     * @Return: int
     **/
    @Transactional(rollbackFor = Exception.class)
    public int insertNewCheck(Integer proId,String director) {
        CheckModel model = new CheckModel();
        model.setProId(proId);
        model.setEqAuditStatus(1);
        model.setEqLaunchTime(new Date());
        model.setLaunchPerson(ShiroUtils.getLoginName());
        model.setEqIsDelete(0);
        model.setDirector(director);
        int i = checkDao.insertNewCheck(model);
        if (i == 1) {
            checkDao.updateProjectCheckStatus(proId);//修改项目 是否发起验收状态值为1
            //todo 修改项目状态表  acceptance_status = 2
            //checkDao.updateStatus(proId, "acceptance_status", 2);
            checkDao.updateAcceptanceStatus(proId,2);
            logService.saveLog("项目发起验收", "项目编号：" + checkDao.queryProCodeByProId(proId + ""));
        }
        return i;
    }

    /**
     * @Description: selcetProInfoByProId 根据项目id查询项目基本信息
     * @Author: zcb
     * @Date: 2020-12-28 09:19:12
     * @Param: [proId]
     * @Return: com.zhongwang.sale.module.afterSale.model.ProjectModel
     **/
    public ProjectModel selcetProInfoByProId(Integer proId) {
        return checkDao.selcetProInfoByProId(proId);
    }

    /**
     * @Description: addDetail 新建验收明细数据
     * @Author: zcb
     * @Date: 2020-12-29 15:52:38
     * @Param: [checkModel]
     * @Return: int
     **/
    public int addDetail(CheckModel checkModel) {
        return checkDao.addDetail(checkModel);
    }

    /**
     * 查询验收单明细
     */
    public int selectDetailByCheckId(int cId) {
        return checkDao.selectDetailByCheckId(cId);
    }

    /**
     * 技术资料说明表 增加一条记录
     */
    public int addTechnical(FileModel fileModel) {
        return checkDao.addTechnical(fileModel);
    }

    /**
     * 验收单编辑保存创建
     */
    @Transactional(rollbackFor = Exception.class)
    public String editSave(CheckModel checkModel,
                           int[] annexType, String[] fileName, String[] relevantDepartment, String[] finishDate, String[] uploadRemark,
                           String[] tempUrl2, String[] fileName2, String[] uploader2, String[] uploadTime2, String[] uploadRemark2) {

        String res = "";
        try {
            //TODO 先查  是否是初次保存  若不是  修改 明细表、技术资料表 数据
            Integer dId = checkDao.selectCheckDetailByCheckId(checkModel.getCheckId());
            boolean flag = false; //是否 创建 明细表数据 标识
            if (dId != null && dId != 0) {
                //修改对应CheckId的 明细表数据
                checkDao.updateDetailByCheckId(checkModel);
                flag = true;
                //删除 对应detailId的 技术资料表数据  在后续再次插入新数据
                checkDao.deleteTechByDetailId(checkModel.getCheckDetailId());
                logService.saveLog("编辑验收单数据", "验收单id：" + checkModel.getCheckId());
            }
            //修改验收状态  点击保存按钮 => 2保存未提交
            checkDao.updateCheckStatusById(checkModel.getCheckId(), 2);
            if (!flag) {
                checkModel.setEqEditPerson(ShiroUtils.getUser().getName());
                addDetail(checkModel); //新建验收明细数据
                logService.saveLog("创建验收单数据", "验收单id：" + checkModel.getCheckId());
            }
            if (annexType != null) {
                int l1 = annexType.length;
                for (int i = 0; i < l1; i++) {
                    if (annexType[i] != 0) {
                        FileModel fileModel = new FileModel();
                        fileModel.setDetailId(checkModel.getCheckDetailId());
                        fileModel.setAnnexType(annexType[i]);
                        fileModel.setFileName(fileName[i]);
                        fileModel.setRelevantDepartment(relevantDepartment[i]);
                        fileModel.setFinishDate(finishDate[i]);
                        fileModel.setUploadRemark(uploadRemark[i]);
                        addTechnical(fileModel);//技术资料说明表 增加一条记录
                    }
                }
            }
            if (tempUrl2 != null) {
                if (tempUrl2.length > 0) {
                    int l2 = tempUrl2.length;
                    for (int i = 0; i < l2; i++) {
                        FileModel fileModel = new FileModel();
                        StringBuffer dir = new StringBuffer();
                        dir.append(uploadPath).append(checkModel.getCheckDetailId()).append("/");
                        try {
                            org.apache.commons.io.FileUtils.moveToDirectory(new File(tempUrl2[i]), new File(dir.toString()), true);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        StringBuffer srcPart = new StringBuffer();
                        srcPart.append(uploadPath).append(ShiroUtils.getLoginName()).append("/temp/");
                        StringBuffer targetPart = new StringBuffer();
                        targetPart.append("/files/").append(checkModel.getCheckDetailId()).append("/");
                        fileModel.setFileUrl(tempUrl2[i].replace(srcPart.toString(), targetPart.toString()));
                        fileModel.setFileName(fileName2[i]);
                        fileModel.setFileComment(uploadRemark2[i]);
                        fileModel.setFileType(1);
                        fileModel.setFileUploadDate(uploadTime2[i]);
                        fileModel.setUserName(uploader2[i]);
                        fileModel.setFileStatus(1);
                        fileModel.setUserId(ShiroUtils.getUserId());
                        fileModel.setMainId(checkModel.getCheckDetailId());
                        checkDao.addFileInfo(fileModel);// 上传附件
                    }
                }
            }
            res = "保存成功";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }

    /***
     * @Description: selectCheckDetailByProId 查询验收单信息 by proid
     * @Author: zcb
     * @Date: 2020-12-30 08:20:59
     * @Param: [proId]
     * @Return: com.zhongwang.sale.module.afterSale.model.CheckModel
     **/
    public CheckModel selectCheckDetailByProId(Integer proId) {
        return checkDao.selectCheckDetailByProId(proId);
    }

    /***
     * @Description: selectTechByDetailId
     * @Author: zcb
     * @Date: 2020-12-30 10:40:33
     * @Param: [checkDetailId]
     * @Return: java.util.List<com.zhongwang.sale.module.afterSale.model.FileModel>
     **/
    public List<FileModel> selectTechByDetailId(int checkDetailId) {
        return checkDao.selectTechByDetailId(checkDetailId);
    }

    /***
     * @Description: selectFileInfoByDetailId
     * @Author: zcb
     * @Date: 2020-12-30 10:40:36
     * @Param: [checkDetailId]
     * @Return: java.util.List<com.zhongwang.sale.module.afterSale.model.FileModel>
     **/
    public List<FileModel> selectFileInfoByDetailId(int checkDetailId, int fileType) {
        return checkDao.selectFileInfoByDetailId(checkDetailId, fileType);
    }


    /***
     * @Description: uploadFile  附件上传 （真上传）
     * @Author: zcb
     * @Date: 2020-12-30 14:38:56
     * @Param: [file, checkDetailId, remark]
     * @Return: int
     **/
    @Transactional(rollbackFor = Exception.class)
    public int uploadFile(MultipartFile[] file, Integer checkDetailId, String remark, int fileType) {
        if (null != file && file.length > 0) {
            for (MultipartFile f : file) {
                String path = uploadPath + checkDetailId + "/";
                String fileName = FileUtils.upload(f, path);
                if (StringUtils.isNotNull(fileName)) {
                    String url = "/files/" + checkDetailId + "/" + fileName;
                    FileModel fileModel = new FileModel();
                    fileModel.setMainId(checkDetailId);
                    fileModel.setFileName(fileName);
                    fileModel.setFileComment(remark);
                    fileModel.setFileType(fileType);
                    fileModel.setFileUrl(url);
                    fileModel.setUserId(ShiroUtils.getUserId());
                    fileModel.setUserName(ShiroUtils.getUser().getName());
                    fileModel.setFileUploadDate(new Date().toString());
                    fileModel.setFileStatus(1);
                    logService.saveLog("上传技术协议附件，", "文件名称：" + fileName
                            + "项目编号：" + checkDao.queryProCodeByProId(checkDetailId + ""));
                    return checkDao.addFileInfo2(fileModel);
                }
            }
        }
        return 0;

    }


    /**
     * @Description: delFileById 附件删除
     * @Author: zcb
     * @Date: 2021-01-04 15:47:47
     * @Param: [fileId]
     * @Return: java.lang.String
     **/
    @Transactional(rollbackFor = Exception.class)
    public String delFileById(Integer fileId) {
        String result = "";
        int i = checkDao.delFileById(fileId);
        if (i == 1) {
            result = "删除成功";
            logService.saveLog("删除附件，", "附件Id =" + fileId);
            return result;
        }
        result = "删除失败";
        return result;
    }

    /**
     * @Description: submitCheck 验收单提交
     * @Author: zcb
     * @Date: 2021-01-05 13:35:34
     * @Param: [proId]
     * @Return: int
     **/
    public int submitCheck(Integer proId) {
        return checkDao.submitCheck(proId);
    }

    /**
     * @Description: ExamineCheck 验收单审核
     * @Author: zcb
     * @Date: 2021-01-05 18:17:20
     * @Param: [checkId]
     * @Return: int
     **/
    @Transactional(rollbackFor = Exception.class)
    public int ExamineCheck(Integer checkId, String eqAuditOpinoin, int status) {
        User user = ShiroUtils.getUser();
        checkDao.updateExamineInfoByCheckId(checkId, eqAuditOpinoin, user.getName());
        int proId = checkDao.selectProIdByCheckId(checkId);

        if (status == 4) {
            //审核通过
            //todo 修改项目状态表 acceptance_status=3
//            checkDao.updateStatus(proId, "acceptance_status", 3);
            checkDao.updateAcceptanceStatus(proId,3);
            checkDao.updateAcceptanceOverTime(proId);
            logService.saveLog("验收单审核通过,", "项目编号：" + checkDao.queryProCodeByProId(proId + ""));
        } else if (status == 2) {
            //驳回
            logService.saveLog("验收单审核驳回,", "项目编号：" + checkDao.queryProCodeByProId(proId + ""));
        }
        return checkDao.updateCheckStatusById(checkId, status);
    }

    /***
     * @Description: selectBoHuiInfoByProId 查询驳回信息
     * @Author: zcb
     * @Date: 2021-01-06 15:10:15
     * @Param: [proId]
     * @Return: com.zhongwang.sale.module.afterSale.model.CheckModel
     **/
    public CheckModel selectBoHuiInfoByProId(Integer proId) {
        return checkDao.selectBoHuiInfoByProId(proId);
    }

    /**
     * @Description: selectTechList 查询技术资料管理页列表
     * @Author: zcb
     * @Date: 2021-01-06 18:51:54
     * @Param: [projectModel]
     * @Return: java.util.List<com.zhongwang.sale.module.afterSale.model.ProjectModel>
     **/
    public List<ProjectModel> selectTechList(ProjectModel projectModel) {
        return checkDao.selectTechList(projectModel);
    }

    /**
     * @Description: updateProTechStatus 修改技术文件上传状态
     * @Author: zcb
     * @Date: 2021-01-06 20:40:20
     * @Param: [proId]
     * @Return: int
     **/
    @Transactional(rollbackFor = Exception.class)
    public int updateProTechStatus(int proId) {
        //todo 修改项目状态表 technical_status=3  上传一个文件   -->  已完成
//        checkDao.updateStatus(proId, "technical_status", 3);
        checkDao.updateTechnicalStatus(proId,3);
        checkDao.updateTechnicalOverTime(proId);
        return checkDao.updateProTechStatus(proId);
    }


    /**
     * @Description: selectAnnexList 技术协议附件列表
     * @Author: zcb
     * @Date: 2021-01-07 08:42:34
     * @Param: [proId]
     * @Return: java.util.List<com.zhongwang.sale.module.afterSale.model.FileModel>
     **/
    public List<FileModel> selectAnnexList(int proId) {
        return checkDao.selectAnnexList(proId);
    }


    /**
     * @Description: techIsNeedSave 保存  是否需要技术协议
     * @Author: zcb
     * @Date: 2021-01-11 15:13:46
     * @Param: [proId]
     * @Return: int
     **/
    public int techIsNeedSave(int proId, int proTechAgreement) {
        int alUpdateNum = checkDao.queryFileCount(proId, 2);
        String proCode = checkDao.queryProCodeByProId(proId + "");
        if (proTechAgreement == 3) {
            //前台传来proTechAgreement=3  下拉框为不需要   修改项目状态表 technical_status=3
            //checkDao.updateStatus(proId, "technical_status", 0);
            checkDao.updateTechnicalStatus(proId,0);
            logService.saveLog("修改项目技术协议为 【不需要】", "项目编号：" + proCode);
            return checkDao.techIsNeedSave(proId, proTechAgreement);
        } else {
            logService.saveLog("修改项目技术协议为 【需要】", "项目编号：" + proCode);
            if (alUpdateNum == 0) {
//                checkDao.updateStatus(proId, "technical_status", 1);
                checkDao.updateTechnicalStatus(proId,1);
                return checkDao.techIsNeedSave(proId, 2);
            } else {
//                checkDao.updateTechnicalStatus(proId,3);
//                checkDao.updateTechnicalOverTime(proId);
                return checkDao.techIsNeedSave(proId, 1);
            }
        }
    }

    public int queryCount(Integer fileId, int i) {
        return checkDao.queryCount(fileId, i);
    }

    public int queryProId(Integer fileId) {
        return checkDao.queryProId(fileId);
    }

    public void updateTechStatus(int proId) {
//        checkDao.updateStatus(proId, "technical_status", 1);
        checkDao.updateTechnicalStatus(proId,1);
        checkDao.updateTechStatus(proId);
    }

    public User getUserByName(String director) {
       return checkDao.getUserByName(director);
    }
}
